package com.thon.service.user.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thon.dao.user.MessageDao;
import com.thon.dao.user.UserDao;
import com.thon.dao.util.Page;
import com.thon.entity.user.Message;
import com.thon.entity.user.User;
import com.thon.service.user.MessageService;

@Service
@Transactional
public class MessageServiceImpl implements MessageService {
	
	@Autowired
	private MessageDao messageDao;
	
	@Autowired
	private UserDao userDao;

	@Override
	public Page<Message> pageMessageTo(int userId, int pageNo, int pageSize) {
		Page<Message> page = new Page<Message>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		List<Message> ms=new ArrayList<Message>();
		if(page.getResult()!=null){
			for(Message m:page.getResult()){
				m.setMessageFrom(userDao.getUser(m.getMessageFrom().getId()));
				m.setMessageTo(userDao.getUser(m.getMessageTo().getId()));
				ms.add(m);
			}
			page.setResult(ms);
		}
		return messageDao.findMessagesPage(page, userId);
	}

	@Override
	public void deleteMessage(int messageId) {
		
		messageDao.delete(messageId);
		
	}

	@Override
	public Long countUnreadMessage(Integer userId) {
		return messageDao.countMessage(userId);
	}

	@Override
	public Message getMessage(Integer id) {
		return messageDao.get(id);
	}

	@Override
	public void updateMessage(Message message) {

		messageDao.update(message);
	}

	@Override
	public void sendMessage(User from, User to, String content) {
		Message message = new Message();
		message.setCreatedDate(new Date());
		message.setContent(content);
		message.setMessageFrom(from);
		message.setMessageTo(to);
		messageDao.save(message);
	}

}
